/**
 * Copyright (C) 2011 PROCESSBASE Ltd.
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GPL as published by the Free Software Foundation version 3 of the License.
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, see <http://www.gnu.org/licenses/>.
 */
package org.processbase.touchprocess.ui.navigator;

import com.vaadin.data.Item;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Table;
import com.vaadin.ui.themes.BaseTheme;
import java.util.Collection;
import java.util.Date;
import org.ow2.bonita.facade.runtime.ActivityState;
import org.ow2.bonita.light.LightTaskInstance;
import org.processbase.touchprocess.ui.template.NavigationList;
import org.processbase.touchprocess.ui.template.TaskButton;
import org.processbase.touchprocess.ui.TouchProcessApplication;
import org.processbase.touchprocess.ui.generator.BarResource;
import org.processbase.touchprocess.ui.generator.GeneratedLayout;
import org.processbase.ui.core.bonita.forms.XMLProcessDefinition;
import org.processbase.ui.core.bonita.forms.XMLTaskDefinition;

/**
 *
 * @author mgubaidullin
 */
public class TaskListNavigationView extends NavigationList {

    @Override
    public void initUI() {
        super.initUI();
        table.addContainerProperty("type", Button.class, null);
        table.setColumnWidth("type", 25);
        table.setColumnAlignment("type", Table.ALIGN_RIGHT);
        table.addContainerProperty("task", TaskButton.class, null);
        table.addContainerProperty("lastUpdate", Date.class, null);
        table.setVisibleColumns(new Object[]{"type", "task"});
        table.setColumnExpandRatio("task", 1);
    }

    @Override
    public void refreshTable() {
        table.removeAllItems();
        try {
            Collection<LightTaskInstance> tasks = TouchProcessApplication.getCurrent().getBpmModule().getLightTaskList(ActivityState.READY);
            tasks.addAll(TouchProcessApplication.getCurrent().getBpmModule().getLightTaskList(ActivityState.EXECUTING));
            tasks.addAll(TouchProcessApplication.getCurrent().getBpmModule().getLightTaskList(ActivityState.SUSPENDED));
            for (LightTaskInstance task : tasks) {
                Item item = table.addItem(task.getUUID());
                TaskButton btn = new TaskButton(task);
                btn.addListener(this);
                item.getItemProperty("task").setValue(btn);
                Button btnIcon = new Button(null);
                btnIcon.setStyleName(BaseTheme.BUTTON_LINK);
                btnIcon.setIcon(getResource(task));
                item.getItemProperty("type").setValue(btnIcon);
                item.getItemProperty("lastUpdate").setValue(task.getLastUpdateDate());
            }
            this.rowCount = tasks.size();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        table.setSortContainerPropertyId("lastUpdate");
        table.setSortAscending(false);
        table.sort();
        setCaption("TaskList (" + rowCount + ")");
    }

    private ThemeResource getResource(LightTaskInstance task) {
        ThemeResource icon = null;
        if (!task.isTaskAssigned()) {
            icon = new ThemeResource("icons/email.png");
        } else if (task.getState().equals(ActivityState.SUSPENDED) && task.getPriority() == 0) {
            icon = new ThemeResource("icons/pause_normal.png");
        } else if (task.getState().equals(ActivityState.SUSPENDED) && task.getPriority() == 1) {
            icon = new ThemeResource("icons/pause_high.png");
        } else if (task.getState().equals(ActivityState.SUSPENDED) && task.getPriority() == 2) {
            icon = new ThemeResource("icons/pause_urgent.png");
        } else if (task.getState().equals(ActivityState.EXECUTING) && task.getPriority() == 0) {
            icon = new ThemeResource("icons/arrow_right_normal.png");
        } else if (task.getState().equals(ActivityState.EXECUTING) && task.getPriority() == 1) {
            icon = new ThemeResource("icons/arrow_right_high.png");
        } else if (task.getState().equals(ActivityState.EXECUTING) && task.getPriority() == 2) {
            icon = new ThemeResource("icons/arrow_right_urgent.png");
        } else if (task.getState().equals(ActivityState.READY) && task.getPriority() == 0) {
            icon = new ThemeResource("icons/arrow_right_normal.png");
        } else if (task.getState().equals(ActivityState.READY) && task.getPriority() == 1) {
            icon = new ThemeResource("icons/arrow_right_high.png");
        } else if (task.getState().equals(ActivityState.READY) && task.getPriority() == 2) {
            icon = new ThemeResource("icons/arrow_right_urgent.png");
        } else {
            icon = new ThemeResource("icons/empty.png");
        }
        return icon;
    }

    @Override
    public void layoutClick(LayoutClickEvent event) {
        super.layoutClick(event);
        try {
            TaskButton btn = (TaskButton) event.getSource();
            LightTaskInstance task = btn.getTask();
            LightTaskInstance newTask = TouchProcessApplication.getCurrent().getBpmModule().getTaskInstance(task.getUUID());
            if (newTask == null || newTask.getState().equals(ActivityState.FINISHED) || newTask.getState().equals(ActivityState.ABORTED)) {
                table.removeItem(task.getUUID());
            } else {
                table.setValue(task.getUUID());
                openTaskLayout(task);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            showError(ex.toString());
        }
    }

    public void openTaskLayout(LightTaskInstance task) {
        try {
            BarResource barResource = new BarResource(task.getProcessDefinitionUUID());
            XMLProcessDefinition xmlProcess = barResource.getXmlProcessDefinition();
            XMLTaskDefinition taskDef = xmlProcess.getTasks().get(task.getActivityName());
            if (taskDef != null && !taskDef.isSkipEntryPageFlow() /*check that forms is defined*/) {
                GeneratedLayout generatedLayout = new GeneratedLayout();
                generatedLayout.setTask(TouchProcessApplication.getCurrent().getBpmModule().getTaskInstance(task.getUUID()));
                generatedLayout.setBarResource(barResource);
                TouchProcessApplication.getCurrent().getMobileMainWindow().getMainView().getDetailsView().setDetailsLayout(generatedLayout);
                generatedLayout.initUI();
            } else if (taskDef != null && taskDef.isSkipEntryPageFlow()) {
                TouchProcessApplication.getCurrent().getBpmModule().startTask(task.getUUID(), true);
                TouchProcessApplication.getCurrent().getBpmModule().finishTask(task.getUUID(), true);
                showImportantInformation(TouchProcessApplication.getCurrent().getPbMessages().getString("taskExecuted"));
                refreshTable();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            showError(ex.getMessage());
        }

    }
}
